/**
 * Copyright &copy; 2012-2017 <a href="https://vivo.com/">vivo</a> All rights reserved.
 */
package com.vivo.system.web;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolationException;

import com.thinkgem.jeesite.modules.sys.entity.User;
import com.thinkgem.jeesite.modules.sys.utils.UserUtils;
import com.vivo.Utils.CommonUtils;
import com.vivo.Utils.HttpUtil;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.google.common.collect.Lists;
import com.thinkgem.jeesite.common.utils.DateUtils;
import com.thinkgem.jeesite.common.config.Global;
import com.thinkgem.jeesite.common.persistence.Page;
import com.thinkgem.jeesite.common.web.BaseController;
import com.thinkgem.jeesite.common.utils.StringUtils;
import com.thinkgem.jeesite.common.utils.excel.ExportExcel;
import com.thinkgem.jeesite.common.utils.excel.ImportExcel;
import com.vivo.system.entity.ViEmpInvite;
import com.vivo.system.service.ViEmpInviteService;

import java.net.URLEncoder;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 邀约记录Controller
 * @author jyangye
 * @version 2018-03-08
 */
@Controller
@RequestMapping(value = "${adminPath}/system/viEmpInvite")
public class ViEmpInviteController extends BaseController {

	@Autowired
	private ViEmpInviteService viEmpInviteService;
	
	@ModelAttribute
	public ViEmpInvite get(@RequestParam(required=false) String id) {
		ViEmpInvite entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = viEmpInviteService.get(id);
		}
		if (entity == null){
			entity = new ViEmpInvite();
		}
		return entity;
	}
	
	@RequiresPermissions("system:viEmpInvite:view")
	@RequestMapping(value = {"list", ""})
	public String list(ViEmpInvite viEmpInvite, HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<ViEmpInvite> page = viEmpInviteService.findPage(new Page<ViEmpInvite>(request, response), viEmpInvite); 
		model.addAttribute("page", page);
		return "vivo/system/viEmpInviteList";
	}

	@RequiresPermissions("system:viEmpInvite:view")
	@RequestMapping(value = "form")
	public String form(ViEmpInvite viEmpInvite, Model model) {
		model.addAttribute("viEmpInvite", viEmpInvite);
		return "vivo/system/viEmpInviteForm";
	}

	@RequiresPermissions("system:viEmpInvite:edit")
	@RequestMapping(value = "save")
	public String save(ViEmpInvite viEmpInvite, Model model, RedirectAttributes redirectAttributes) {
		if (!beanValidator(model, viEmpInvite)){
			return form(viEmpInvite, model);
		}
		viEmpInviteService.save(viEmpInvite);
		addMessage(redirectAttributes, "保存邀约记录成功");
		return "redirect:"+Global.getAdminPath()+"/system/viEmpInvite/?repage";
	}
	
	@RequiresPermissions("system:viEmpInvite:edit")
	@RequestMapping(value = "delete")
	public String delete(ViEmpInvite viEmpInvite, RedirectAttributes redirectAttributes) {
		viEmpInviteService.delete(viEmpInvite);
		addMessage(redirectAttributes, "删除邀约记录成功");
		return "redirect:"+Global.getAdminPath()+"/system/viEmpInvite/?repage";
	}

    @ResponseBody
    @RequestMapping(value = "saveInvite")
    public Map<String, Object> saveInvite(@RequestParam(required=true) String name,
                                        @RequestParam(required=true) String phone,
                                        @RequestParam(required=true) String sms) {

	    Map<String, Object> retMap = new HashMap<String, Object>();

	    ViEmpInvite empInvite = new ViEmpInvite();
	    empInvite.setComp(UserUtils.getUser().getCompany());
	    empInvite.setCreatedAt(new Date());
	    empInvite.setEmpId(UserUtils.getUser().getId());
	    empInvite.setName(name);
	    empInvite.setPhone(phone);
	    empInvite.setSms(sms);
	    empInvite.setOperator(UserUtils.getUser().getName());

	    String msg = "ok";
	    int retVal = 0;

	    try {
            viEmpInviteService.save(empInvite);

            CommonUtils.sendSMSMsg(phone, sms);
        } catch (Exception e) {
	        msg = e.getMessage();
	        retVal = -1;
        }

        retMap.put("msg", msg);
	    retMap.put("ret", retVal);

	    return retMap;
    }

    @ResponseBody
    @RequestMapping(value = "getShortUrl")
    public String shortUrl(@RequestParam(required=true) String url) {
	    try {
            url = "http://api.t.sina.com.cn/short_url/shorten.json?source=3271760578&url_long=" + URLEncoder.encode(url, "UTF-8");
        }catch (Exception e) {
	        e.printStackTrace();
        }
	    return HttpUtil.get(url);
    }

	/**
	 * 批量删除邀约记录
	 */
	@RequiresPermissions("system:viEmpInvite:edit")
	@RequestMapping(value = "deleteAll")
	public String deleteAll(String ids, RedirectAttributes redirectAttributes) {
		String idArray[] =ids.split(",");
		for(String id : idArray){
			viEmpInviteService.delete(viEmpInviteService.get(id));
		}
		addMessage(redirectAttributes, "删除邀约记录成功");
		return "redirect:"+Global.getAdminPath()+"/system/viEmpInvite/?repage";
	}

	/**
	 * 导出excel文件
	 */
	@RequiresPermissions("system:viEmpInvite:edit")
    @RequestMapping(value = "export", method=RequestMethod.POST)
    public String exportFile(ViEmpInvite viEmpInvite, HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
            String fileName = "邀约记录"+DateUtils.getDate("yyyyMMddHHmmss")+".xlsx";
            Page<ViEmpInvite> page = viEmpInviteService.findPage(new Page<ViEmpInvite>(request, response, -1), viEmpInvite);
    		new ExportExcel("邀约记录", ViEmpInvite.class).setDataList(page.getList()).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导出邀约记录记录失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/system/viEmpInvite/?repage";
    }

	/**
	 * 导入Excel数据

	 */
	@RequiresPermissions("system:viEmpInvite:edit")
    @RequestMapping(value = "import", method=RequestMethod.POST)
    public String importFile(MultipartFile file, RedirectAttributes redirectAttributes) {
		try {
			int successNum = 0;
			int failureNum = 0;
			StringBuilder failureMsg = new StringBuilder();
			ImportExcel ei = new ImportExcel(file, 1, 0);
			List<ViEmpInvite> list = ei.getDataList(ViEmpInvite.class);
			for (ViEmpInvite viEmpInvite : list){
				try{
					viEmpInviteService.save(viEmpInvite);
					successNum++;
				}catch(ConstraintViolationException ex){
					failureNum++;
				}catch (Exception ex) {
					failureNum++;
				}
			}
			if (failureNum>0){
				failureMsg.insert(0, "，失败 "+failureNum+" 条邀约记录记录。");
			}
			addMessage(redirectAttributes, "已成功导入 "+successNum+" 条邀约记录记录"+failureMsg);
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入邀约记录失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/system/viEmpInvite/?repage";
    }

	/**
	 * 下载导入{functionNameSimple}数据模板
	 */
	@RequiresPermissions("system:viEmpInvite:edit")
    @RequestMapping(value = "import/template")
    public String importFileTemplate(HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
            String fileName = "邀约记录数据导入模板.xlsx";
    		List<ViEmpInvite> list = Lists.newArrayList();
    		new ExportExcel("邀约记录数据", ViEmpInvite.class, 2).setDataList(list).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入模板下载失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/system/viEmpInvite/?repage";
    }

}